
--[[
	**********************
	* SvFrame - thomasfn *
	**********************
	kickban.lua - Loads basic kick and ban functionality
]]

function PLUGIN:InitKickBan()
	svr.AddFlag( "cankick" )
	svr.AddFlag( "canban" )
	
	self:Command( "kick", self.Kick, { FLAG_CANKICK } )
	self:Command( "ban", self.Ban,  { FLAG_CANBAN } )
	
	self:Hook( "player.connect", self.PlayerConnect )
end

table.insert( PLUGIN.Inits, PLUGIN.InitKickBan )

function PLUGIN:Kick( ply, args )
	if (not svr.CheckArg( args, 1, "string" )) then return ply:ChatPrint( colour.White, "Syntax: /kick <name> [reason]" ) end
	local plist = svr.FindPlayers( args[1] )
	if (#plist == 0) then return ply:ChatPrint( colour.Red, "No players found with that name." ) end
	if (#plist > 1) then return ply:ChatPrint( colour.Red, "Multiple players found with that partial name." ) end
	table.remove( args, 1 )
	local reason = table.concat( args, " " )
	if (reason == "") then reason = "Kicked by " .. ply.Username end
	svr.ChatPrint( nil, plist[1].Username .. " was kicked by " .. ply.Username .. " (" .. reason .. ")" )
	plist[1].Kick( reason )
end

function PLUGIN:Ban( ply, args )
	if (not svr.CheckArg( args, 1, "string" )) then return ply:ChatPrint( colour.White, "Syntax: /ban <name> [hours]" ) end
	local plist = svr.FindPlayers( args[1] )
	if (#plist == 0) then return ply:ChatPrint( colour.Red, "No players found with that name." ) end
	if (#plist > 1) then return ply:ChatPrint( colour.Red, "Multiple players found with that partial name." ) end
	local verb = "banned"
	local howlong = tonumber( args[2] ) or 0
	if (howlong == 0) then verb = "perma-banned" end
	local reason = svr.NameToTitle( verb ) .. " by " .. ply.Username .. "."
	local start = svr.Time()
	print( "Banning for " .. (howlong * 3600) .. " seconds, start = " ..start )
	if (howlong > 0) then
		reason = reason .. " (" .. howlong .. " hours)"
		svr.SetPlayerPData( plist[1], "BanEnd", start + (howlong * 3600) )
	else
		svr.SetPlayerPData( plist[1], "BanEnd", -1 )
	end
	svr.ChatPrint( nil, plist[1].Username .. " was ", colour.Red, verb, colour.White, " by " .. ply.Username .. "." )
	plist[1].Kick( reason )
end

function PLUGIN:PlayerConnect( ply )
	local banend = svr.GetPlayerPDataN( ply, "BanEnd" ) or 0
	if (banend == 0) then return end
	if (banend == -1) then return ply:Kick( "You are perma-banned from this server." ) end
	if (banend <= svr.Time()) then
		Timers.Create( 3, 1, ply.Username .. "_BanMessage", function()
			ply:ChatPrint( colour.Red, "Your ban has expired. Behave, or the next time might be permanent." )
		end )
		svr.SetPlayerPData( ply, "BanEnd", 0 )
	else
		ply.Kick( "You are banned from this server." )
	end
end